package zero.tech.wsnet.net;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.Session;

import zero.tech.core.ZeroContext;
import zero.tech.core.event.service.api.EventService;
import zero.tech.wsnet.controller.CacheOnline;
import zero.tech.wsnet.controller.Controller;
import zero.tech.wsnet.data.Consts;
import zero.tech.wsnet.data.NetEventType;

public class CacheClient {
	public static final Map<String, WebClient> clients = new ConcurrentHashMap<String, WebClient>();

	public static void add(WebClient webClient) {
		String sessionId = webClient.getSessionId();
		clients.put(sessionId, webClient);
	}

	public static void remove(WebClient webClient) {
		WebClient remove = clients.remove(webClient.getSessionId());
		if (remove != null) {
			Controller controller = webClient.getController();
			if (controller != null) {
				int playerId = controller.getId();
				Controller con = CacheOnline.getCache().getOnlines().get(playerId);
				if (con != null) {
					if(con.getWebClient().getSession()==null||con.equals(controller)) {
						CacheOnline.getCache().offline(controller);
						EventService netEventService = ZeroContext.getInstance(EventService.class);
						netEventService.engineNotify(NetEventType.ENGINE_PLAYER_OFFLINE, controller);
					}
				}
			}
			remove.setController(null);
			remove=null;
		}
	}

	public static WebClient getWebClient(Session session) {
		return (WebClient) session.getUserProperties().get(Consts.SESSION_PK_WEBCLIENT);
	}
}
